import React, { PureComponent, Fragment } from 'react';
import dynamic from 'umi/dynamic';
import { connect } from 'dva';
import QueueAnim from 'rc-queue-anim';
import { Form, Input, Button, Card, Modal, message } from 'antd';
import DescriptionList from '@/components/DescriptionList';
import Step2Banners from './Step2Banners';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Description } = DescriptionList;

const CreateForm = Form.create()(props => {
  const { modalVisible, handleUpdate } = props;
  return (
    <Modal
      destroyOnClose
      width={1300}
      visible={modalVisible}
      footer={null}
      bodyStyle={{padding: 0}}
    >
      <Step2Banners onChange={handleUpdate} />
    </Modal>
  );
});

@connect(({ profile, loading }) => ({
  profile,
  // submitting: loading.effects['form/submitRegularForm'],
  submitting: loading.models.profile,
}))
@Form.create()
class BasicForms extends PureComponent {

  state = {
    modalVisible: false,
  }

  handleSubmit = e => {
    e.preventDefault();

    const { dispatch, form, profile: { data = {} } } = this.props;

    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        dispatch({
          type: 'profile/update',
          payload: { ...values, id: data.id, type: 1 },
          callback({ errno }) {
            if (errno) {
              message.error('提交失败');
            } else {
              message.success('奖品配置并上首页成功~');
            }
          }
        });
      }
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag
    });
  };

  handleUpdate = payload => {
    const { dispatch, profile: { data = {} } } = this.props
    const { id } = data;

    const values = Object.assign({}, data, { Banner: { ...payload, goodsId: id } });

    dispatch({
      type: 'profile/save',
      payload: values,
    });

    this.setState({
      modalVisible: false,
    }, () => message.success('选择关联广告成功~'));
  };

  render() {
    const { modalVisible } = this.state;

    const {
      submitting,
      form: { getFieldDecorator },
      profile: { data },
    } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    const parentMethods = {
      modalVisible,
      handleUpdate: this.handleUpdate,
      handleModalVisible: this.handleModalVisible,
    };

    const sty = {
      width: '100%',
      height: 150,
      marginTop: 16,
      marginBottom: 16,
      borderRadius: 6,
      backgroundSize: 'cover',
      backgroundPosition: 'center',
      backgroundRepeat: 'no-repeat',
      boxShadow: '1px 3px 5px rgba(0,0,0,.1)'
    }

    return (
      <Fragment>
        <Card title="首页配置" bordered={false}>
          <QueueAnim delay={300} component={Form} onSubmit={this.handleSubmit} hideRequiredMark style={{ minHeight: 300, marginTop: 8 }}>
            <FormItem {...formItemLayout} label="赞助商名称" key="sponsor">
              {getFieldDecorator('sponsor', {
                initialValue: data.sponsor,
                rules: [
                  {
                    required: true,
                    message: "请输入赞助商名称",
                  },
                ],
              })(<Input placeholder="请输入赞助商名称" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="关联小程序 ID" key="sponsorId">
              {getFieldDecorator('appId', {
                initialValue: data.appId,
                rules: [
                  {
                    required: true,
                    message: "请输入关联小程序 ID",
                  },
                ],
              })(<Input placeholder="请输入关联小程序 ID" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="备注" key="remark">
              {getFieldDecorator('remark', {
                initialValue: data.remark,
                rules: [
                  {
                    required: true,
                    message: "请输入备注",
                  },
                ],
              })(
                <TextArea
                  style={{ minHeight: 32 }}
                  placeholder="请输入备注"
                  rows={4}
                />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="关联广告" key="banners">
              <Button icon="link" type="primary" ghost onClick={this.handleModalVisible}>关联广告</Button>
              {
                data.Banner
                &&
                <section>
                  <section style={{...sty, backgroundImage: `url(${data.Banner.cover + IMAGE_STYLE})`}} />
                  <DescriptionList size="small" col="2">
                    <Description term="上架日期">{data.Banner.createdAt}</Description>
                    <Description term="下架日期">{data.Banner.endAt}</Description>
                    <Description term="关联小程序 APPID">{data.Banner.appId ? data.Banner.appId : '/'}</Description>
                  </DescriptionList>
                </section>                
              }
            </FormItem>
            
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" htmlType="submit" loading={submitting} size="large" style={{width: '100%'}}>
                确认配置
              </Button>
            </FormItem>
          </QueueAnim>
        </Card>
        <CreateForm {...parentMethods} />
      </Fragment>
    );
  }
}

export default dynamic({
  loader: async () => payload => <BasicForms {...payload} />,
});